<template>
  <div>
    <el-form inline>
      <el-form-item label="一级分类">
        <el-select
          v-model="category1Id"
          :disabled="flag"
          placeholder="请选择"
          @change="cate1Change"
        >
          <el-option
            :label="cate1.name"
            :value="cate1.id"
            v-for="cate1 in category1List"
            :key="cate1.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          v-model="category2Id"
          :disabled="flag"
          placeholder="请选择"
          @change="cate2Change"
        >
          <el-option
            :label="cate2.name"
            :value="cate2.id"
            v-for="cate2 in category2List"
            :key="cate2.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          v-model="category3Id"
          :disabled="flag"
          placeholder="请选择"
          @change="cate3Change"
        >
          <el-option
            :label="cate3.name"
            :value="cate3.id"
            v-for="cate3 in category3List"
            :key="cate3.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  name: "Category",
  props: ["flag"],

  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
    };
  },
  computed: {
    ...mapState({
      category1List: (state) => state.category.category1List,
      category2List: (state) => state.category.category2List,
      category3List: (state) => state.category.category3List,
      category1IdStore: (state) => state.category.category1Id,
      category2IdStore: (state) => state.category.category2Id,
      category3IdStore: (state) => state.category.category3Id,
    }),
  },

  // 挂载的时候
  async mounted() {
    // 调用actions函数
    await this.getCategory1List();
    this.categoryId();
  },

  methods: {
    ...mapActions("category", [
      "getCategory1List",
      "getCategory2List",
      "getCategory3List",
    ]),
    // 初始化各个ID
    categoryId() {
      this.category1Id = this.category1IdStore;
      this.category2Id = this.category2IdStore;
      this.category3Id = this.category3IdStore;
    },

    // 改变分类1的函数
    async cate1Change() {
      await this.getCategory2List(this.category1Id);
      // 改变一级分类的时候，后面那两个就要重新选，将后面两个的categoryId设置为空
      this.category2Id = "";
      this.category3Id = "";
    },

    // 改变分类2的函数
    async cate2Change() {
      // 传入分类2的ID，获取分类3的列表
      await this.getCategory3List(this.category2Id);
      this.category3Id = "";
    },

    // 改变分类3的触发函数
    async cate3Change() {
      // 改变仓库的3id
      this.$store.commit("category/UPDATE_3ID", this.category3Id);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-right: 40px;
}
</style>
